package com.leyou.auth.controller;

import com.leyou.auth.service.AuthService;
import com.leyou.common.auth.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping
public class AuthController {

    @Autowired
    private AuthService authService;

    /**
     * 登录要做的事情：1，验证用户名和密码
     *                 2，生成jwt的token
     *                 3，把jwt存入到cookie中
     * 注意：springmvc内部封装很多对象，比如：Model，ModelAndView，还有原生的servletApi对象
     *       HttpServletResponse， HttpServletRequest
     *       这些对象只要写在处理器【controller中的方法】的方法参数中，直接可以使用。
     * @return
     */
    @PostMapping("/login")
    public ResponseEntity<Void> login(@RequestParam("username") String username,
                                      @RequestParam("password") String password,
                                      HttpServletResponse response){
        authService.login(username, password, response);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 验证的思路：获取Cookie
     * @return
     */
    @GetMapping("/verify")
    public ResponseEntity<UserInfo> verify(HttpServletRequest request, HttpServletResponse response){
        return ResponseEntity.ok(authService.verify(request, response));
    }

    /**
     * 退出登录操作
     */
    @PostMapping("/logout")
    public ResponseEntity<Void> logout(@CookieValue("LY_TOKEN") String token, HttpServletResponse response){
        authService.logout(token, response);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }
}
